﻿namespace MicroCloud.AspNetCore.Mvc.Filters
{
    /// <summary>
    /// 自动提交工作单元事务，在<see cref="ActionFilterAttribute.OnResultExecuted"/>方法中执行<see cref="IUnitOfWork.Commit()"/>进行事务提交
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class UnitOfWorkAttribute : ServiceFilterAttribute
    {
        #region 构造函数
        /// <summary>
        /// 自动提交工作单元事务
        /// <para>在 <see cref="ActionFilterAttribute.OnResultExecuted"/> 方法中执行 <see cref="IUnitOfWork.Commit()"/> 进行事务提交</para>
        /// </summary>
        /// <param name="immediate">立即开启事务</param>
        /// <param name="isolationLevel">事务隔离级别</param>
        public UnitOfWorkAttribute(bool immediate, IsolationLevel isolationLevel)
            : this()
        {
            Immediate = immediate;
            IsolationLevel = isolationLevel;
        }

        /// <summary>
        /// 自动提交工作单元事务
        /// <para>在 <see cref="ActionFilterAttribute.OnResultExecuted"/> 方法中执行 <see cref="IUnitOfWork.Commit()"/> 进行事务提交</para>
        /// </summary>
        /// <param name="immediate">立即开启事务</param>
        public UnitOfWorkAttribute(bool immediate)
            : this()
        {
            Immediate = immediate;
            IsolationLevel = null;
        }

        /// <summary>
        /// 自动提交工作单元事务
        /// <para>在 <see cref="ActionFilterAttribute.OnResultExecuted"/> 方法中执行 <see cref="IUnitOfWork.Commit()"/> 进行事务提交</para>
        /// </summary>
        /// <param name="isolationLevel">事务隔离级别</param>
        public UnitOfWorkAttribute(IsolationLevel isolationLevel)
            : this(false, isolationLevel)
        { }

        /// <summary>
        /// 自动提交工作单元事务
        /// <para>在 <see cref="ActionFilterAttribute.OnResultExecuted"/> 方法中执行 <see cref="IUnitOfWork.Commit()"/> 进行事务提交</para>
        /// </summary>
        public UnitOfWorkAttribute()
            : base(typeof(UnitOfWorkImpl))
        {
            Immediate = false;
            IsolationLevel = null;
        }

        #endregion

        #region 属性
        /// <summary>
        /// 获取 立即开启事务
        /// </summary>
        public bool Immediate { get; } = false;

        /// <summary>
        /// 获取 事务隔离级别
        /// </summary>
        public IsolationLevel? IsolationLevel { get; } = null;

        #endregion

    }
}